﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using bmapi.HelperClass;

namespace bmapi.Controllers
{
    
    public class DownLogController : PageController
    {
        /// <summary>
        /// 下载日志文件
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("downdebug")]
        public HttpResponseMessage Get()
        {
            try
            {
                //客户端保存的文件名  
                string filename = m_buyiRoot + "\\buyiUpload\\debug.log";


                if (!File.Exists(filename))
                   return  AssistFun.toJson(new {status=201,tip="暂时没有产生错误文件" });

                //以字符流的形式下载文件  
                FileStream fs = new FileStream(filename, FileMode.Open);
                byte[] bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                //通知浏览器下载文件而不是打开 
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode("debug.log", System.Text.Encoding.UTF8));
                HttpContext.Current.Response.BinaryWrite(bytes);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
                //File.WriteAllText(filename, string.Empty);
                return AssistFun.toJson(new { status = 200, tip = "成功" });
            }
            catch (Exception e)
            {
               return AssistFun.toJson(new { status = 201, tip = e.Message });
            }            
        }
        
    }
}
